package service

import (
	"log"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_check/handler"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_check/model"
	"github.com/lzppppppp/virapaksa-go/internal/monitor_check/repository"
	"github.com/spf13/viper"
)

func PostPortCheckServer(context *gin.Context) {

	var param handler.CheckDataServer
	err := context.BindJSON(&param) // 前后端交互参数
	if err != nil {                 // 错误处理
		log.Printf("ERROR: Port check failed, error is %v", err)
		context.JSON(500, gin.H{"err": err})
		return
	}

	ipParts := strings.Split(param.IP, "\n")
	log.Println("INFO: The ip for check is ", ipParts)

	var reOutCome string

	if param.Dc != "" {

		checkDataAgent := handler.CheckDataAgent{
			Type: param.Type,
			IP:   ipParts,
		}

		var targetUrlB strings.Builder
		targetUrlB.WriteString("http://")
		targetUrlB.WriteString(viper.GetString("check_node." + param.Dc))
		targetUrlB.WriteString(":7777/v1/check/")
		targetUrlB.WriteString(param.Ctype)
		targetUrlB.WriteString("Agent")
		targetUrl := targetUrlB.String()

		reOutCome, _ = handler.PostData(checkDataAgent, targetUrl)
	} else {
		dc2dc := map[string]string{
			"北京数据中心":    "pek",
			"内蒙数据中心":    "nm",
			"上海数据中心":    "sh",
			"合肥数据中心":    "hf",
			"内蒙数据中心-和林": "nm-zj",
		}

		dcIpMap := make(map[string][]string)

		for _, ipValue := range ipParts {
			if ipValue != "" {
				DB := repository.GetDB()
				var Data []model.CmdbAllServer
				DB.Table("cmdb_all_servers").Where("ip = ?", ipValue).Find(&Data) // 根据IP，从mysql库中获取数据
				if len(Data) == 0 {
					log.Printf("WARNING: %v not find in cmdb", ipValue)
				} else {
					dcIpMap[dc2dc[Data[0].Datacenter]] = append(dcIpMap[dc2dc[Data[0].Datacenter]], ipValue)
				}

			}
		}

		for dc, ipArr := range dcIpMap {

			checkDataAgent := handler.CheckDataAgent{
				Type:    param.Type,
				IP:      ipArr,
				TimeOut: param.TimeOut,
			}

			var targetUrlB strings.Builder
			targetUrlB.WriteString("http://")
			targetUrlB.WriteString(viper.GetString("check_node." + dc))
			targetUrlB.WriteString(":7777/v1/check/")
			targetUrlB.WriteString(param.Ctype)
			targetUrlB.WriteString("Agent")
			targetUrl := targetUrlB.String()

			reOutComeSingleDc, _ := handler.PostData(checkDataAgent, targetUrl)
			reOutCome = reOutCome + reOutComeSingleDc
		}

	}
	log.Printf(reOutCome)
	data := handler.JsonData{
		Code: 200,
		Data: reOutCome,
	}
	context.JSON(http.StatusOK, data)
}
